<template>
  <el-form label-width="100">
    <el-form-item label="SPU名称">
      <el-input
        v-model="spuParams.spuName"
        placeholder="请输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select style="width: 200px" v-model="spuParams.tmId">
        <el-option
          v-for="item in trademarkList"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请输入SPU描述"
        v-model="spuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU照片">
      <el-upload
        v-model:file-list="spuImageList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        style="width: 200px; margin-right: 10px"
        :placeholder="
          unSelectedSaleAttrList.length
            ? `还有${unSelectedSaleAttrList.length}个未选择`
            : '暂无数据可选择'
        "
        v-model="unSelectedSaleAttr"
      >
        <el-option
          v-for="item in unSelectedSaleAttrList"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        size="default"
        icon="plus"
        :disabled="!unSelectedSaleAttr"
        @click="handleAddSaleAttr"
      >
        添加销售属性
      </el-button>
      <el-table style="margin: 10px 0" :data="spuSaleAttrList" border>
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 0 5px"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag"
              style="width: 100px"
              placeholder="请输入属性值"
              v-model="row.saleAttrValue"
              size="small"
              @blur="toLook(row)"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="plus"
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="default"
              icon="delete"
              @click="spuSaleAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="default"
        :disabled="!(spuSaleAttrList.length > 0)"
        @click="handleSave"
      >
        保存
      </el-button>
      <el-button size="default" @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts" name="SpuForm">
import { ref, computed } from 'vue'
import { SpuData } from '@/api/product/spu/type'
import {
  getAllTrademarkApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  getBaseSaleAttrListApi,
  addOrUpdateSpuApi,
} from '@/api/product/spu/index'
import {
  TrademarkList,
  AllTrademark,
  SpuImage,
  SpuImageList,
  SpuImageResponseData,
  SpuSaleAttr,
  SpuSaleAttrList,
  SpuSaleAttrResponseData,
  BaseSpuSaleAttr,
  BaseSpuSaleAttrList,
  BaseSpuSaleAttrResponseData,
  SpuSaleAttrValue,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'

const $emit = defineEmits(['changeScene'])
// 数据
const trademarkList = ref<TrademarkList>([])
const spuImageList = ref<SpuImageList>([])
const spuSaleAttrList = ref<SpuSaleAttrList>([])
const baseSpuSaleAttrList = ref<BaseSpuSaleAttrList>([])
const spuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
const dialogVisible = ref<boolean>(false)
const dialogImageUrl = ref<string>('')
// 未选择的销售属性的id和名字(id:name)
const unSelectedSaleAttr = ref<string>('')

// 方法
const handleCancel = () => {
  $emit('changeScene', {
    scene: 0, // 场景切换
    pageFlag: 'update', // 是否翻页
  })
}
const handleSave = async () => {
  // 整理照片数据
  spuParams.value.spuImageList = spuImageList.value.map((item: SpuImage) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  // 销售属性数据
  spuParams.value.spuSaleAttrList = spuSaleAttrList.value

  const res = await addOrUpdateSpuApi(spuParams.value)

  if (res.code == 200) {
    ElMessage.success(spuParams.value.id ? '更新成功' : '添加成功')
    $emit('changeScene', {
      scene: 0, // 场景切换
      pageFlag: spuParams.value.id ? 'update' : 'add', // 是否翻页
    })
  } else {
    ElMessage.error(spuParams.value.id ? '更新失败' : '添加失败')
  }
}
// 初始化SPU数据
const initSpuData = async (spuData: SpuData) => {
  spuParams.value = spuData
  // 获取全部品牌
  const res: AllTrademark = await getAllTrademarkApi()
  // 获取SPU的图片列表
  const res1: SpuImageResponseData = await getSpuImageListApi(spuData.id)
  // 获取SPU的销售属性列表
  const res2: SpuSaleAttrResponseData = await getSpuSaleAttrListApi(spuData.id)
  // 获取全部销售属性
  const res3: BaseSpuSaleAttrResponseData = await getBaseSaleAttrListApi()
  trademarkList.value = res.data
  spuImageList.value = res1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  spuSaleAttrList.value = res2.data
  baseSpuSaleAttrList.value = res3.data
}
// 添加一个新的SPU初始化请求方法
const initAddSpu = async (category3Id: number | string) => {
  // 清空数据
  Object.assign(spuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
    id: '',
  })
  spuImageList.value = []
  spuSaleAttrList.value = []
  unSelectedSaleAttr.value = ''
  // 存储三级分类ID
  spuParams.value.category3Id = category3Id
  // 获取全部品牌
  const res: AllTrademark = await getAllTrademarkApi()
  // 获取全部销售属性
  const res1: BaseSpuSaleAttrResponseData = await getBaseSaleAttrListApi()
  trademarkList.value = res.data
  baseSpuSaleAttrList.value = res1.data
}
// 图片预览点击事件
const handlePictureCardPreview = (file: any) => {
  dialogVisible.value = true
  dialogImageUrl.value = file.url
}
// 图片删除点击事件
const handleRemove = () => {}
// 图片上传事件
const beforeUpload = (rawFile: any) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('请上传图片（jpg/png/git）')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('图片大小不能超过4MB')
    return false
  }
  return true
}
// 添加属性按钮点击事件
const handleAddSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = unSelectedSaleAttr.value.split(':')
  let newSaleAttr: SpuSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  spuSaleAttrList.value.push(newSaleAttr)
  unSelectedSaleAttr.value = ''
}
// 当前SPU未拥有的销售属性
const unSelectedSaleAttrList = computed(() => {
  let unSelectedArr = baseSpuSaleAttrList.value.filter(
    (item: BaseSpuSaleAttr) => {
      return spuSaleAttrList.value.every((item1: SpuSaleAttr) => {
        return item.name != item1.saleAttrName
      })
    },
  )
  return unSelectedArr
})
// 添加销售属性值按钮点击事件
const toEdit = (row: SpuSaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
// 添加属性值输入框失焦事件
const toLook = (row: SpuSaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row

  let newSaleAttrValue: SpuSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }

  // 不能为空
  if (saleAttrValue?.trim() == '') {
    ElMessage.error('属性值不能为空')
    return
  }
  // 是否重名
  let repeat = row.spuSaleAttrValueList.find((item: SpuSaleAttrValue) => {
    return item.saleAttrName == saleAttrValue
  })
  if (repeat) {
    ElMessage.error('属性值不能重复')
    return
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue)

  row.flag = false
}
defineExpose({ initSpuData, initAddSpu })
</script>

<style scoped lang="scss"></style>
